package com.example.arithmeticleetcode.learnArithmetic2.sort;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-11-06 13:26
 **/
public class BinarySearch {

    /**
     * 在有序数组中找到所传值的位置
     *
     * @param array
     * @param v
     * @return
     */
    public static int indexOf(int[] array, int v) {
        if (array == null || array.length < 2) return -1;
        int begin = 0;
        int end = array.length;
        while (end > begin) {
            int mid = (end + begin) >> 1;
            if (array[mid] > v) {
                end = mid;
            } else if (array[mid] < v) {
                begin = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    /**
     * 查找v所在有序数组array中待插入位置
     *
     * @param array
     * @param v
     * @return
     */
    public static int searh(int[] array, int v) {
        if (array == null || array.length < 2) return -1;
        int begin = 0;
        int end = array.length;
        while (begin < end) {
            int mid = (begin + end) >> 1;
            if (v < array[mid]) {
                end = mid;
            } else {
                begin = mid + 1;
            }
        }
        return begin;
    }
}
